package com.jianganming.netty.long_coder;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;


public class LongCoderServer {
    public static void main(String[] args) {
        EventLoopGroup group1 = new NioEventLoopGroup(1);
        EventLoopGroup group2 = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        try {
            ChannelFuture future = bootstrap.group(group1, group2)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            pipeline.addLast(new ByteToLongDecoder());
                            pipeline.addLast(new LongToByteEncoder());
                            pipeline.addLast(new SimpleChannelInboundHandler<Long>() {
                                @Override
                                protected void channelRead0(ChannelHandlerContext ctx, Long aLong) throws Exception {
                                    System.out.println(ctx.channel().remoteAddress()+"读到   "+aLong);
                                    ctx.writeAndFlush(aLong+123);
                                }

                                @Override
                                public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                                    cause.printStackTrace();
                                    ctx.close();

                                }
                            });
                        }
                    }).bind(8889).sync();
            future.channel().closeFuture().sync();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            group1.shutdownGracefully();
            group2.shutdownGracefully();
        }
    }
}
